<template>
  <div class="settings-management">
    <el-tabs v-model="activeTab" class="settings-tabs">
      <!-- 营业时间设置 -->
      <el-tab-pane label="营业时间设置" name="businessHours">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>营业时间设置</span>
              <el-button type="primary" @click="handleAddBusinessHours">新增时间段</el-button>
            </div>
          </template>
          
          <el-table :data="businessHoursList" stripe style="width: 100%">
            <el-table-column prop="dayOfWeek" label="星期">
              <template #default="scope">
                {{ getDayOfWeekName(scope.row.dayOfWeek) }}
              </template>
            </el-table-column>
            <el-table-column prop="openTime" label="开业时间" width="120" />
            <el-table-column prop="closeTime" label="打烊时间" width="120" />
            <el-table-column prop="isClosed" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isClosed === 0 ? 'success' : 'danger'">
                  {{ scope.row.isClosed === 0 ? '营业' : '休息' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="handleEditBusinessHours(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteBusinessHours(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
      
      <!-- 配送管理 -->
      <el-tab-pane label="配送管理" name="delivery">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>配送范围和费用设置</span>
              <el-button type="primary" @click="handleAddDeliveryConfig">新增配送配置</el-button>
            </div>
          </template>
          
          <el-table :data="deliveryConfigList" stripe style="width: 100%">
            <el-table-column prop="rangeFrom" label="起始距离(公里)" width="150" />
            <el-table-column prop="rangeTo" label="结束距离(公里)" width="150" />
            <el-table-column prop="deliveryFee" label="配送费用(元)" width="150" />
            <el-table-column prop="isActive" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isActive === 1 ? 'success' : 'danger'">
                  {{ scope.row.isActive === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="handleEditDeliveryConfig(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteDeliveryConfig(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
      
      <!-- 优惠活动 -->
      <el-tab-pane label="优惠活动" name="promotion">
        <el-tabs v-model="promotionActiveTab" type="card">
          <el-tab-pane label="优惠券管理" name="coupon">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>优惠券管理</span>
                  <el-button type="primary" @click="handleAddCoupon">新增优惠券</el-button>
                </div>
              </template>
              
              <el-table :data="couponList" stripe style="width: 100%">
                <el-table-column prop="name" label="优惠券名称" />
                <el-table-column prop="type" label="类型" width="120">
                  <template #default="scope">
                    {{ scope.row.type === 1 ? '满减券' : '折扣券' }}
                  </template>
                </el-table-column>
                <el-table-column prop="discountAmount" label="减免金额" width="120">
                  <template #default="scope">
                    {{ scope.row.type === 1 ? '¥' + scope.row.discountAmount : '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="discountRate" label="折扣率" width="120">
                  <template #default="scope">
                    {{ scope.row.type === 2 ? scope.row.discountRate * 10 + '折' : '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="minAmount" label="最低消费" width="120">
                  <template #default="scope">
                    ¥{{ scope.row.minAmount }}
                  </template>
                </el-table-column>
                <el-table-column prop="validDays" label="有效天数" width="120" />
                <el-table-column prop="totalQuantity" label="总数量" width="100" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                      {{ scope.row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template #default="scope">
                    <el-button size="small" @click="handleEditCoupon(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDeleteCoupon(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-tab-pane>
          
          <el-tab-pane label="满减活动" name="promotionActivity">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>满减活动管理</span>
                  <el-button type="primary" @click="handleAddPromotion">新增活动</el-button>
                </div>
              </template>
              
              <el-table :data="promotionList" stripe style="width: 100%">
                <el-table-column prop="name" label="活动名称" />
                <el-table-column prop="threshold" label="满足金额" width="120">
                  <template #default="scope">
                    ¥{{ scope.row.threshold }}
                  </template>
                </el-table-column>
                <el-table-column prop="discount" label="减免金额" width="120">
                  <template #default="scope">
                    ¥{{ scope.row.discount }}
                  </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始时间" width="180" />
                <el-table-column prop="endTime" label="结束时间" width="180" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                      {{ scope.row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template #default="scope">
                    <el-button size="small" @click="handleEditPromotion(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDeletePromotion(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
      
      <!-- 通知管理 -->
      <el-tab-pane label="通知管理" name="notice">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>系统通知管理</span>
              <el-button type="primary" @click="handleAddNotice">新增通知</el-button>
            </div>
          </template>
          
          <el-table :data="noticeList" stripe style="width: 100%">
            <el-table-column prop="title" label="通知标题" />
            <el-table-column prop="type" label="类型" width="120">
              <template #default="scope">
                {{ scope.row.type === 1 ? '系统公告' : '订单提醒' }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="handleEditNotice(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteNotice(scope.row)">删除</el-button>
                <el-button size="small" type="primary" @click="handleToggleNoticeStatus(scope.row)">
                  {{ scope.row.status === 1 ? '禁用' : '启用' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 营业时间编辑对话框 -->
    <el-dialog v-model="businessHoursDialogVisible" :title="businessHoursDialogTitle" width="500px">
      <el-form :model="currentBusinessHours" label-width="100px">
        <el-form-item label="星期">
          <el-select v-model="currentBusinessHours.dayOfWeek" placeholder="请选择星期">
            <el-option
              v-for="day in daysOfWeek"
              :key="day.value"
              :label="day.label"
              :value="day.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开业时间">
          <el-time-picker
            v-model="currentBusinessHours.openTime"
            value-format="HH:mm:ss"
            format="HH:mm"
            placeholder="选择开业时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="打烊时间">
          <el-time-picker
            v-model="currentBusinessHours.closeTime"
            value-format="HH:mm:ss"
            format="HH:mm"
            placeholder="选择打烊时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="currentBusinessHours.isClosed"
            :active-value="0"
            :inactive-value="1"
            active-text="营业"
            inactive-text="休息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="businessHoursDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveBusinessHours">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 配送配置编辑对话框 -->
    <el-dialog v-model="deliveryConfigDialogVisible" :title="deliveryConfigDialogTitle" width="500px">
      <el-form :model="currentDeliveryConfig" label-width="120px">
        <el-form-item label="起始距离(公里)">
          <el-input-number
            v-model="currentDeliveryConfig.rangeFrom"
            :min="0"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束距离(公里)">
          <el-input-number
            v-model="currentDeliveryConfig.rangeTo"
            :min="0"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="配送费用(元)">
          <el-input-number
            v-model="currentDeliveryConfig.deliveryFee"
            :min="0"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="currentDeliveryConfig.isActive"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deliveryConfigDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDeliveryConfig">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 优惠券编辑对话框 -->
    <el-dialog v-model="couponDialogVisible" :title="couponDialogTitle" width="600px">
      <el-form :model="currentCoupon" label-width="120px">
        <el-form-item label="优惠券名称">
          <el-input v-model="currentCoupon.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-radio-group v-model="currentCoupon.type">
            <el-radio :label="1">满减券</el-radio>
            <el-radio :label="2">折扣券</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="currentCoupon.type === 1">
          <el-form-item label="减免金额(元)">
            <el-input-number
              v-model="currentCoupon.discountAmount"
              :min="0"
              :precision="2"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="折扣率">
            <el-input-number
              v-model="currentCoupon.discountRate"
              :min="0"
              :max="1"
              :precision="2"
              :step="0.1"
              style="width: 100%"
            />
          </el-form-item>
        </div>
        <el-form-item label="最低消费金额">
          <el-input-number
            v-model="currentCoupon.minAmount"
            :min="0"
            :precision="2"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="有效天数">
          <el-input-number
            v-model="currentCoupon.validDays"
            :min="1"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="总发行数量">
          <el-input-number
            v-model="currentCoupon.totalQuantity"
            :min="1"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="currentCoupon.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="couponDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCoupon">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 满减活动编辑对话框 -->
    <el-dialog v-model="promotionDialogVisible" :title="promotionDialogTitle" width="600px">
      <el-form :model="currentPromotion" label-width="120px">
        <el-form-item label="活动名称">
          <el-input v-model="currentPromotion.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="满足金额">
          <el-input-number
            v-model="currentPromotion.threshold"
            :min="0"
            :precision="2"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="减免金额">
          <el-input-number
            v-model="currentPromotion.discount"
            :min="0"
            :precision="2"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="currentPromotion.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="currentPromotion.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="currentPromotion.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="promotionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePromotion">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 通知编辑对话框 -->
    <el-dialog v-model="noticeDialogVisible" :title="noticeDialogTitle" width="600px">
      <el-form :model="currentNotice" label-width="100px">
        <el-form-item label="通知标题">
          <el-input v-model="currentNotice.title" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="通知类型">
          <el-select v-model="currentNotice.type" placeholder="请选择通知类型">
            <el-option label="系统公告" :value="1" />
            <el-option label="订单提醒" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知内容">
          <el-input
            v-model="currentNotice.content"
            type="textarea"
            :rows="4"
            placeholder="请输入通知内容"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="currentNotice.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="noticeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNotice">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getBusinessHoursList,
  addBusinessHours,
  updateBusinessHours,
  deleteBusinessHours,
  getDeliveryConfigList,
  addDeliveryConfig,
  updateDeliveryConfig,
  deleteDeliveryConfig,
  getCouponList,
  addCoupon,
  updateCoupon,
  deleteCoupon,
  getPromotionList,
  addPromotion,
  updatePromotion,
  deletePromotion,
  getNoticeList,
  addNotice,
  updateNotice,
  deleteNotice,
  toggleNoticeStatus
} from '@/api/settings'

// 激活的标签页
const activeTab = ref('businessHours')
const promotionActiveTab = ref('coupon')

// 营业时间数据
const businessHoursList = ref([])
const businessHoursDialogVisible = ref(false)
const businessHoursDialogTitle = ref('')
const currentBusinessHours = reactive({
  id: 0,
  dayOfWeek: 1,
  openTime: '09:00:00',
  closeTime: '22:00:00',
  isClosed: 0
})

// 星期选项
const daysOfWeek = ref([
  { label: '星期一', value: 1 },
  { label: '星期二', value: 2 },
  { label: '星期三', value: 3 },
  { label: '星期四', value: 4 },
  { label: '星期五', value: 5 },
  { label: '星期六', value: 6 },
  { label: '星期日', value: 7 }
])

// 获取星期名称
const getDayOfWeekName = (dayOfWeek) => {
  const day = daysOfWeek.value.find(d => d.value === dayOfWeek)
  return day ? day.label : ''
}

// 配送配置数据
const deliveryConfigList = ref([])
const deliveryConfigDialogVisible = ref(false)
const deliveryConfigDialogTitle = ref('')
const currentDeliveryConfig = reactive({
  id: 0,
  rangeFrom: 0,
  rangeTo: 0,
  deliveryFee: 0,
  isActive: 1
})

// 优惠券数据
const couponList = ref([])
const couponDialogVisible = ref(false)
const couponDialogTitle = ref('')
const currentCoupon = reactive({
  id: 0,
  name: '',
  type: 1, // 1-满减券，2-折扣券
  discountAmount: 0,
  discountRate: 0.9,
  minAmount: 0,
  validDays: 7,
  totalQuantity: 100,
  status: 1
})

// 满减活动数据
const promotionList = ref([])
const promotionDialogVisible = ref(false)
const promotionDialogTitle = ref('')
const currentPromotion = reactive({
  id: 0,
  name: '',
  type: 1, // 1-满减活动
  threshold: 0,
  discount: 0,
  startTime: '',
  endTime: '',
  status: 1
})

// 通知数据
const noticeList = ref([])
const noticeDialogVisible = ref(false)
const noticeDialogTitle = ref('')
const currentNotice = reactive({
  id: 0,
  title: '',
  content: '',
  type: 1, // 1-系统公告，2-订单提醒
  status: 1
})

// 处理新增营业时间
const handleAddBusinessHours = () => {
  businessHoursDialogTitle.value = '新增营业时间'
  Object.assign(currentBusinessHours, {
    id: 0,
    dayOfWeek: 1,
    openTime: '09:00:00',
    closeTime: '22:00:00',
    isClosed: 0
  })
  businessHoursDialogVisible.value = true
}

// 处理编辑营业时间
const handleEditBusinessHours = (row) => {
  businessHoursDialogTitle.value = '编辑营业时间'
  Object.assign(currentBusinessHours, row)
  businessHoursDialogVisible.value = true
}

// 保存营业时间
const saveBusinessHours = async () => {
  try {
    let response
    if (currentBusinessHours.id === 0) {
      // 新增
      response = await addBusinessHours(currentBusinessHours)
    } else {
      // 编辑
      response = await updateBusinessHours(currentBusinessHours)
    }
    
    if (response.code === 200) {
      ElMessage.success('营业时间保存成功')
      businessHoursDialogVisible.value = false
      loadBusinessHoursList()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 处理删除营业时间
const handleDeleteBusinessHours = (row) => {
  ElMessageBox.confirm(`确定要删除${getDayOfWeekName(row.dayOfWeek)}的营业时间设置吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteBusinessHours(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadBusinessHoursList()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理新增配送配置
const handleAddDeliveryConfig = () => {
  deliveryConfigDialogTitle.value = '新增配送配置'
  Object.assign(currentDeliveryConfig, {
    id: 0,
    rangeFrom: 0,
    rangeTo: 0,
    deliveryFee: 0,
    isActive: 1
  })
  deliveryConfigDialogVisible.value = true
}

// 处理编辑配送配置
const handleEditDeliveryConfig = (row) => {
  deliveryConfigDialogTitle.value = '编辑配送配置'
  Object.assign(currentDeliveryConfig, row)
  deliveryConfigDialogVisible.value = true
}

// 保存配送配置
const saveDeliveryConfig = async () => {
  try {
    let response
    if (currentDeliveryConfig.id === 0) {
      // 新增
      response = await addDeliveryConfig(currentDeliveryConfig)
    } else {
      // 编辑
      response = await updateDeliveryConfig(currentDeliveryConfig)
    }
    
    if (response.code === 200) {
      ElMessage.success('配送配置保存成功')
      deliveryConfigDialogVisible.value = false
      loadDeliveryConfigList()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 处理删除配送配置
const handleDeleteDeliveryConfig = (row) => {
  ElMessageBox.confirm('确定要删除该配送配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteDeliveryConfig(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadDeliveryConfigList()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理新增优惠券
const handleAddCoupon = () => {
  couponDialogTitle.value = '新增优惠券'
  Object.assign(currentCoupon, {
    id: 0,
    name: '',
    type: 1,
    discountAmount: 0,
    discountRate: 0.9,
    minAmount: 0,
    validDays: 7,
    totalQuantity: 100,
    status: 1
  })
  couponDialogVisible.value = true
}

// 处理编辑优惠券
const handleEditCoupon = (row) => {
  couponDialogTitle.value = '编辑优惠券'
  Object.assign(currentCoupon, row)
  couponDialogVisible.value = true
}

// 保存优惠券
const saveCoupon = async () => {
  try {
    let response
    if (currentCoupon.id === 0) {
      // 新增
      response = await addCoupon(currentCoupon)
    } else {
      // 编辑
      response = await updateCoupon(currentCoupon)
    }
    
    if (response.code === 200) {
      ElMessage.success('优惠券保存成功')
      couponDialogVisible.value = false
      loadCouponList()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 处理删除优惠券
const handleDeleteCoupon = (row) => {
  ElMessageBox.confirm('确定要删除该优惠券吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteCoupon(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadCouponList()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理新增促销活动
const handleAddPromotion = () => {
  promotionDialogTitle.value = '新增促销活动'
  Object.assign(currentPromotion, {
    id: 0,
    name: '',
    type: 1,
    threshold: 0,
    discount: 0,
    startTime: '',
    endTime: '',
    status: 1
  })
  promotionDialogVisible.value = true
}

// 处理编辑促销活动
const handleEditPromotion = (row) => {
  promotionDialogTitle.value = '编辑促销活动'
  Object.assign(currentPromotion, row)
  promotionDialogVisible.value = true
}

// 保存促销活动
const savePromotion = async () => {
  try {
    let response
    if (currentPromotion.id === 0) {
      // 新增
      response = await addPromotion(currentPromotion)
    } else {
      // 编辑
      response = await updatePromotion(currentPromotion)
    }
    
    if (response.code === 200) {
      ElMessage.success('促销活动保存成功')
      promotionDialogVisible.value = false
      loadPromotionList()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 处理删除促销活动
const handleDeletePromotion = (row) => {
  ElMessageBox.confirm('确定要删除该促销活动吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deletePromotion(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadPromotionList()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理新增通知
const handleAddNotice = () => {
  noticeDialogTitle.value = '新增通知'
  Object.assign(currentNotice, {
    id: 0,
    title: '',
    content: '',
    type: 1,
    status: 1
  })
  noticeDialogVisible.value = true
}

// 处理编辑通知
const handleEditNotice = (row) => {
  noticeDialogTitle.value = '编辑通知'
  Object.assign(currentNotice, row)
  noticeDialogVisible.value = true
}

// 保存通知
const saveNotice = async () => {
  try {
    let response
    if (currentNotice.id === 0) {
      // 新增
      response = await addNotice(currentNotice)
    } else {
      // 编辑
      response = await updateNotice(currentNotice)
    }
    
    if (response.code === 200) {
      ElMessage.success('通知保存成功')
      noticeDialogVisible.value = false
      loadNoticeList()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 处理删除通知
const handleDeleteNotice = (row) => {
  ElMessageBox.confirm('确定要删除该通知吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteNotice(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadNoticeList()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理切换通知状态
const handleToggleNoticeStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '禁用'
  
  ElMessageBox.confirm(`确定要${action}该通知吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await toggleNoticeStatus(row.id, newStatus)
      if (response.code === 200) {
        row.status = newStatus
        ElMessage.success(`${action}成功`)
      } else {
        ElMessage.error(response.message || `${action}失败`)
      }
    } catch (error) {
      ElMessage.error(`${action}失败: ` + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 加载营业时间列表
const loadBusinessHoursList = async () => {
  try {
    const response = await getBusinessHoursList()
    if (response.code === 200) {
      businessHoursList.value = response.data
    } else {
      ElMessage.error(response.message || '获取营业时间列表失败')
    }
  } catch (error) {
    ElMessage.error('获取营业时间列表失败: ' + error.message)
  }
}

// 加载配送配置列表
const loadDeliveryConfigList = async () => {
  try {
    const response = await getDeliveryConfigList()
    if (response.code === 200) {
      deliveryConfigList.value = response.data
    } else {
      ElMessage.error(response.message || '获取配送配置列表失败')
    }
  } catch (error) {
    ElMessage.error('获取配送配置列表失败: ' + error.message)
  }
}

// 加载优惠券列表
const loadCouponList = async () => {
  try {
    const response = await getCouponList()
    if (response.code === 200) {
      couponList.value = response.data
    } else {
      ElMessage.error(response.message || '获取优惠券列表失败')
    }
  } catch (error) {
    ElMessage.error('获取优惠券列表失败: ' + error.message)
  }
}

// 加载促销活动列表
const loadPromotionList = async () => {
  try {
    const response = await getPromotionList()
    if (response.code === 200) {
      promotionList.value = response.data
    } else {
      ElMessage.error(response.message || '获取促销活动列表失败')
    }
  } catch (error) {
    ElMessage.error('获取促销活动列表失败: ' + error.message)
  }
}

// 加载通知列表
const loadNoticeList = async () => {
  try {
    const response = await getNoticeList()
    if (response.code === 200) {
      noticeList.value = response.data
    } else {
      ElMessage.error(response.message || '获取通知列表失败')
    }
  } catch (error) {
    ElMessage.error('获取通知列表失败: ' + error.message)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadBusinessHoursList()
  loadDeliveryConfigList()
  loadCouponList()
  loadPromotionList()
  loadNoticeList()
})
</script>

<style scoped>
.settings-management {
  padding: 20px;
}

.settings-tabs {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>